//
//  WBNewFeatrure.swift
//  CustomWeiBo
//
//  Created by laiqiang on 21/5/20.
//  Copyright © 2021年 laiqiang. All rights reserved.
//

import UIKit

//新特性
class WBNewFeatrure: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var enterButtun: UIButton!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBAction func enterwWeiBo() {
        removeFromSuperview()
    }

    
    class func newFeatrure()->WBNewFeatrure {
        
        let nib = UINib(nibName: "WBNewFeatrure", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! WBNewFeatrure
        v.frame = UIScreen.main.bounds
        
        return v
    }
    
    override func awakeFromNib() {
        //使用自动布局设置的界面，默认是600*600
        //添加4个图像视图
        let rect = UIScreen.main.bounds
        let count = 4
        for i in 0..<count {
            
            let imagName = "new_featrure_\(i+1)"
            let imagView = UIImageView.init(image: UIImage.init(named: imagName))
            //设置大小
            imagView.frame = rect.offsetBy(dx: CGFloat(i)*rect.width, dy: 0)
            scrollView.addSubview(imagView)
            scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
            
            scrollView.bounces = false
            scrollView.isPagingEnabled = true
            scrollView.showsVerticalScrollIndicator = false
            scrollView.showsHorizontalScrollIndicator = false
            
            scrollView.delegate = self
            
            enterButtun.isHidden = true
        }
        
        self.addSubview(enterButtun)
        self.addSubview(pageControl)
    }
}

extension WBNewFeatrure :UIScrollViewDelegate{

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        //最后一页
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if page == scrollView.subviews.count {
            removeFromSuperview()
        }

        enterButtun.isHidden = (page != scrollView.subviews.count - 1)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //当前滚动的位置
        enterButtun.isHidden = true
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)
        //分页控件设置
        pageControl.currentPage = page
        pageControl.isHidden = (page == scrollView.subviews.count)
    }

}
